package com.example.studentportrait.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.studentportrait.domain.ResponseResult;
import com.example.studentportrait.domain.dto.SpecialStudentDto;
import com.example.studentportrait.domain.entity.*;
import com.example.studentportrait.domain.vo.PageVo;
import com.example.studentportrait.domain.vo.SpecialStudentVo;
import com.example.studentportrait.mapper.*;
import com.example.studentportrait.service.SpecialStudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import static com.example.studentportrait.enums.AppHttpCodeEnum.SYSTEM_ERROR;


@Service
public class SpecialStudentServiceImpl implements SpecialStudentService {

    @Autowired
    private TeacherStudentMapper teacherStudentMapper;

    @Autowired
    private StudentMapper studentMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private InterviewRecordMapper interviewRecordMapper;

    @Autowired
    private GradeStatisticsMapper gradeStatisticsMapper;

    @Override
    public ResponseResult specialStudentList(Integer pageNum, Integer pageSize, SpecialStudentDto specialStudentDto) {
        // 获取当前登录教师账号
        String teacherAccount = "100513gzu";

        // 查询教师所管理的学生账号
        LambdaQueryWrapper<TeacherStudent> tsWrapper = new LambdaQueryWrapper<>();
        tsWrapper.eq(TeacherStudent::getTeacherAccount, teacherAccount);
        List<String> studentAccounts = teacherStudentMapper.selectList(tsWrapper)
                .stream()
                .map(TeacherStudent::getStudentAccount)
                .collect(Collectors.toList());

        // 如果没有管理的学生，直接返回空分页
        if (studentAccounts.isEmpty()) {
            PageVo emptyPage = new PageVo(Collections.emptyList(), 0L);
            return ResponseResult.okResult(emptyPage);
        }

        // 获取 type 不是“一般”的学生账号
        List<String> filteredStudentAccounts = studentMapper.selectList(new LambdaQueryWrapper<Student>()
                        .in(Student::getAccount, studentAccounts)
                        .ne(Student::getType, "一般"))
                .stream()
                .map(Student::getAccount)
                .collect(Collectors.toList());

        // 如果没有符合条件的学生，直接返回空分页
        if (filteredStudentAccounts.isEmpty()) {
            PageVo emptyPage = new PageVo(Collections.emptyList(), 0L);
            return ResponseResult.okResult(emptyPage);
        }

        // 创建分页对象
        Page<User> pagination = new Page<>(pageNum, pageSize);

        // 构建查询条件
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(User::getAccount, filteredStudentAccounts);

        if (StringUtils.hasText(specialStudentDto.getUserName())) {
            queryWrapper.like(User::getUserName, specialStudentDto.getUserName());
        }

        if (StringUtils.hasText(specialStudentDto.getAccount())) {
            queryWrapper.like(User::getAccount, specialStudentDto.getAccount());
        }

        // 分页查询
        IPage<User> resultPage = userMapper.selectPage(pagination, queryWrapper);

        // 获取查询结果
        List<User> userList = resultPage.getRecords();

        // 获取每个学生的访谈记录
        List<SpecialStudentVo> voList = userList.stream().map(user -> {
            SpecialStudentVo vo = new SpecialStudentVo();
            vo.setUserName(user.getUserName());
            vo.setAccount(user.getAccount());

            // 查询学生信息
            Student student = studentMapper.selectOne(new LambdaQueryWrapper<Student>().eq(Student::getAccount, user.getAccount()));
            if (student != null) {
                vo.setType(student.getType());
                vo.setSeverity(student.getSeverity());
            }

            // 计算访谈记录数量
            int interviewCount = Math.toIntExact(interviewRecordMapper.selectCount(new LambdaQueryWrapper<InterviewRecord>()
                    .eq(InterviewRecord::getAccount, user.getId())));
            vo.setCount(interviewCount);

            return vo;
        }).collect(Collectors.toList());

        // 返回分页结果
        PageVo pageVo = new PageVo(voList, resultPage.getTotal());
        return ResponseResult.okResult(pageVo);
    }

    @Override
    public ResponseResult<SpecialStudentDto> updateSpecialStudent(SpecialStudentDto specialStudentDto) {
        // 更新 Student 表
        LambdaQueryWrapper<Student> studentQueryWrapper = new LambdaQueryWrapper<>();
        studentQueryWrapper.eq(Student::getAccount, specialStudentDto.getAccount());

        Student student = studentMapper.selectOne(studentQueryWrapper);
        if (student == null) {
            return ResponseResult.errorResult(SYSTEM_ERROR);
        }

        student.setType(specialStudentDto.getType());
        student.setSpecialImg(specialStudentDto.getSpecialImg());
        student.setSeverity(specialStudentDto.getSeverity());
        student.setAge(specialStudentDto.getAge());
        student.setMajor(specialStudentDto.getMajor());
        student.setGradeYear(specialStudentDto.getGradeYear());

        studentMapper.updateById(student);

        // 更新 User 表
        LambdaQueryWrapper<User> userQueryWrapper = new LambdaQueryWrapper<>();
        userQueryWrapper.eq(User::getAccount, specialStudentDto.getAccount());

        User user = userMapper.selectOne(userQueryWrapper);
        if (user == null) {
            return ResponseResult.errorResult(SYSTEM_ERROR);
        }

        user.setUserName(specialStudentDto.getUserName());

        userMapper.updateById(user);

//        // 更新 InterviewRecord 表
//        LambdaQueryWrapper<InterviewRecord> interviewQueryWrapper = new LambdaQueryWrapper<>();
//        interviewQueryWrapper.eq(InterviewRecord::getAccount, specialStudentDto.getAccount());
//
//        List<InterviewRecord> interviewRecords = interviewRecordMapper.selectList(interviewQueryWrapper);
//        for (InterviewRecord record : interviewRecords) {
//            record.setInterviewCount(specialStudentDto.);
//            interviewRecordMapper.updateById(record);
//        }
        return ResponseResult.okResult(specialStudentDto);
    }

    @Override
    public ResponseResult<GradeStatistics> gradeStatistics(String account) {
        // 构建查询条件
        LambdaQueryWrapper<GradeStatistics> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(GradeStatistics::getAccount, account);

        // 查询成绩信息
        GradeStatistics gradeStatistics = gradeStatisticsMapper.selectOne(queryWrapper);
        if (gradeStatistics == null) {
            return ResponseResult.errorResult(SYSTEM_ERROR);
        }

        // 返回查询结果
        return ResponseResult.okResult(gradeStatistics);
    }

    @Override
    public ResponseResult<List<InterviewRecord>> interviewRecord(String account) {
        // 构建查询条件
        LambdaQueryWrapper<InterviewRecord> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(InterviewRecord::getAccount, account);

        // 查询访谈记录
        List<InterviewRecord> interviewRecords = interviewRecordMapper.selectList(queryWrapper);
        if (interviewRecords.isEmpty()) {
            return ResponseResult.errorResult(SYSTEM_ERROR);
        }

        // 返回查询结果
        return ResponseResult.okResult(interviewRecords);
    }
}